<!-- 设备维修-维修执行 -->
<template>
  <basic-container class="production-page">
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :defaults.sync="defaults"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      :before-close="beforeClose"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
      :upload-delete="uploadDelete"
      :upload-before="uploadBefore"
      :upload-after="uploadAfter"
    >
      <template slot="resultIdType" slot-scope="{ item }">
        <span>{{ item.name }}({{ item.code }})</span>
      </template>
      <template slot="menuRight">
        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
      </template>
      <template slot="menuLeft">
        <el-button type="primary" plain size="small" :disabled="startDisabled" v-if="permission.maintenanceService_startRepair" @click="handleStart">开始维修</el-button>
        <el-button type="danger" plain size="small" :disabled="endDisabled" v-if="permission.maintenanceService_endRepair" @click="handleEnd">结束维修</el-button>
      </template>
    </avue-crud>
    <global-modal-template :visibile.sync="visibile" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"> </global-modal-template>
  </basic-container>
</template>

<script>
import { mapGetters } from 'vuex';
import { getList, add, update, getDetail, remove, startRepair, endRepair } from '@/api/equipment-manage/maintenanceList';
import GlobalModalTemplate from '@/components/common-modal-template/global-modal-template.vue';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';
export default {
  name: 'EquipmentManageMaintenanceService',
  components: {
    GlobalModalTemplate,
    userTableConfig
  },
  mixins: [userConfig()],
  data() {
    return {
      pageCode: 'MAINTENANCE_SERVICE',
      centerEquipmentId: '',
      handlingId: '',
      visibile: false,
      timer: new Date().getTime(), //不同内容使用同一个模态框结构，key值不同需要重新请求渲染数据，否则会请求到上一个使用的数据内容
      modalName: '', //打开公用模态框名称
      tableOption: {}, //公用模态框配置信息
      endDisabled: true,
      startDisabled: true,
      endFault: false,
      form: { imageList: [] },
      defaults: {},
      query: {},
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        dialogDrag: true,
        height: 'calc(100vh - 440px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        indexLabel: '序号',
        viewBtn: true,
        viewBtnText: '详情',
        viewTitle: '详情',
        excelBtn: false, // 导出
        addBtn: false,
        editBtn: false,
        delBtn: false,
        columnBtn: false,
        selection: true,
        dialogClickModal: false,
        labelWidth: 120,
        menuWidth: 100,
        addTitle: '',
        column: [
          {
            label: '维修单号',
            width: 150,
            prop: 'handlingNo',
            search: true,
            rules: [
              {
                required: true,
                message: '请输入维修单号',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '状态',
            prop: 'status',
            html: true,
            formatter: (val) => {
              switch (val.status) {
                case 2:
                  return `<span class="stateWords-warning">待维修</span>`;
                case 7:
                  return `<span class="stateWords-danger">维修中</span>`;
                case 8:
                  return `<span class="stateWords-success">维修结束</span>`;
                default:
                  break;
              }
            }
          },
          {
            label: '设备编码',
            prop: 'equipmentCode',
            search: true,
            rules: [
              {
                required: true,
                message: '请输入设备编码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '设备名称',
            prop: 'equipmentName',
            search: true,
            rules: [
              {
                required: true,
                message: '请输入设备名称',
                trigger: 'blur'
              }
            ]
          },
          // {
          //   label: '设备类型',
          //   prop: 'equipmentCategory',
          //   type: 'select',
          //   search: true,
          //   rules: [
          //     {
          //       required: true,
          //       message: '请输入设备类型',
          //       trigger: 'blur'
          //     }
          //   ]
          // },
          {
            label: '故障现象',
            prop: 'faultSymptom'
          },
          {
            label: '紧急程度',
            prop: 'urgency',
            type: 'select',
            value: 'GENERAL',
            dicData: [
              { label: '一般', value: 'GENERAL' },
              { label: '紧急', value: 'URGE' }
            ]
          },
          {
            label: '报修人',
            prop: 'repairApplicant'
          },
          {
            label: '报修时间',
            prop: 'repairTime'
          }
        ],
        group: [
          {
            label: '设备信息',
            prop: 'sbxx',
            column: [
              {
                label: '设备编码',
                prop: 'equipmentCode'
              },
              {
                label: '设备名称',
                prop: 'equipmentName'
              }
            ]
          },
          {
            label: '故障登记信息',
            prop: 'gzdjxx',
            column: [
              {
                label: '故障现象',
                prop: 'faultSymptom'
              },
              {
                label: '紧急程度',
                prop: 'urgency',
                type: 'select',
                value: 'GENERAL',
                dicData: [
                  { label: '一般', value: 'GENERAL' },
                  { label: '紧急', value: 'URGE' }
                ]
              },
              {
                label: '报修人',
                prop: 'repairApplicant'
              },
              {
                label: '报修时间',
                prop: 'repairTime'
              },
              {
                label: '故障描述',
                prop: 'remark',
                type: 'textarea',
                minRows: 3,
                maxRows: 3,
                span: 24
              },
              {
                label: '故障图片',
                prop: 'beforeRepairImageList',
                type: 'upload',
                listType: 'picture-card',
                span: 24,
                propsHttp: {
                  res: 'data',
                  url: 'link',
                  name: 'originalName'
                },
                props: {
                  label: '',
                  value: 'link'
                },
                tip: '只能上传png/jpeg/jpg文件且最多上传3张！',
                action: '/api/blade-resource/oss/endpoint/put-file-attach'
              }
            ]
          },
          {
            label: '维修执行登记',
            prop: 'gzdjxx',
            column: [
              {
                label: '故障类型',
                prop: 'resultId',
                type: 'tree',
                dicUrl: '/api/mes-product/mro/dict/tree?dictType=EQUIPMENT&subType=FALUT_TYPE',
                dicData: [],
                props: {
                  label: 'code',
                  value: 'id'
                },
                typeformat(item, label, value) {
                  return `${item['code']}`;
                },
                rules: [
                  {
                    required: true,
                    message: '请输入故障类型',
                    trigger: 'blur'
                  }
                ]
              },
              {
                label: '维修人员',
                prop: 'repairerName',
                disabled: true,
                type: 'search',
                appendClick: () => {
                  this.openUserCommonModal({
                    type: 'repairer'
                  });
                },
                rules: [
                  {
                    required: true,
                    message: '请输入维修人员',
                    trigger: 'blur'
                  }
                ]
              },
              {
                label: '处理措施',
                prop: 'handlingAction',
                type: 'textarea',
                minRows: 3,
                maxRows: 3,
                // maxlength: 500,
                // showWordLimit: true,
                span: 24,
                rules: [
                  {
                    required: true,
                    message: '请输入处理措施',
                    trigger: 'blur'
                  }
                ]
              },
              {
                label: '原因及改善',
                prop: 'suggestion',
                type: 'textarea',
                minRows: 3,
                maxRows: 3,
                // maxlength: 500,
                // showWordLimit: true,
                span: 24
              },
              {
                label: '维修完成图片',
                prop: 'resultRepairImageList',
                type: 'upload',
                listType: 'picture-card',
                loadText: '附件上传中，请稍等',
                span: 24,
                props: {
                  label: '',
                  value: 'link'
                },
                propsHttp: {
                  res: 'data',
                  url: 'link',
                  name: 'originalName'
                },
                tip: '只能上传png/jpeg/jpg文件且最多上传3张！',
                action: '/api/blade-resource/oss/endpoint/put-file-attach'
              }
            ]
          }
        ]
      },
      data: []
    };
  },
  inject: ['reload'],
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        viewBtn: this.vaildData(this.permission.maintenanceService_view, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids;
    }
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  methods: {
    rowSave(row, done, loading) {
      row.imageVOList = row.imageList;
      row.centerEquipmentId = this.centerEquipmentId;
      row.handlingId = this.handlingId;
      row.resultCode = row.$resultId;
      delete row.imageList;
      delete row.resultRepairImageList;
      delete row.beforeRepairImageList;
      delete row.status;
      delete row.handlingNo;
      delete row.faultSymptom;
      delete row.equipmentCode;
      delete row.equipmentName;
      delete row.repairerName;
      delete row.repairTime;
      delete row.repairApplicant;
      delete row.remark;
      endRepair(row).then(
        () => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '结束维修成功，请到维修列表进行查看'
          });
          this.centerEquipmentId = '';
          this.handlingId = '';

          done();
        },
        () => {
          loading();
        }
      );
    },
    handleStart() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确认开始维修?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return startRepair(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    handleEnd() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.option.addTitle = '维修登记';
      this.$set(this.form, 'imageList', []);
      this.endFault = true;
      this.centerEquipmentId = this.selectionList[0].id;
      this.handlingId = this.selectionList[0].handlingId;
      let userData = JSON.parse(localStorage.getItem('saber-userInfo') || '{}').content;
      if (userData) {
        this.form.repairerName = userData.real_name;
        this.form.repairer = userData.user_id;
      }
      this.$refs.crud.rowAdd(this.selectionList[0], this.selectionList[0].$index);
    },
    beforeOpen(done, type) {
      for (const key in this.defaults) {
        this.defaults[key].display = false;
      }
      if (type == 'add') {
        if (this.endFault) {
          this.$set(this.option.group[0], 'display', false);
          this.$set(this.option.group[1], 'display', false);
          this.$set(this.option.group[2], 'display', true);
        } else {
          this.$set(this.option.group[0], 'display', true);
          this.$set(this.option.group[1], 'display', true);
          this.$set(this.option.group[2], 'display', false);
        }
      }
      if (type == 'view') {
        this.$set(this.option.group[0], 'display', true);
        this.$set(this.option.group[1], 'display', true);
        this.$set(this.option.group[2], 'display', false);
        getDetail(this.form.id, this.form.handlingId).then((res) => {
          this.form = res.data.data;
          this.option.group[2].column[0].type = 'input';
          this.form.repairerName = res.data.data.handleBy;
          this.form.resultId = res.data.data.faultType;
        });
      } else {
        this.option.group[2].column[0].type = 'tree';
      }

      done();
    },
    beforeClose(done, type) {
      this.endFault = false;
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
      let isStart = this.selectionList.every((s) => s.status === 2);
      let isEnd = this.selectionList.every((s) => s.status === 7);
      if (this.selectionList && this.selectionList.length > 0 && isStart) {
        this.startDisabled = false;
      } else {
        this.startDisabled = true;
      }
      if (this.selectionList && this.selectionList.length == 1 && isEnd) {
        this.endDisabled = false;
      } else {
        this.endDisabled = true;
      }
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud && this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      this.query.operatorFlag = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    openUserCommonModal(params) {
      let { type } = params;
      switch (type) {
        // 客户信息
        case 'repairer':
          this.modalName = 'repairerModal';
          this.visibile = true;
          this.tableOption = {
            modalTitle: '选择维修人员信息（双击进行选择）',
            url: '/api/blade-system/user/page',
            isPage: true,
            rowSelectionType: 'single',
            menuWidth: 100,
            templateName: 'USER'
          };
          break;
        default:
          break;
      }
    },
    // 获取选择的模态框行数据
    getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'repairerModal':
          this.form.repairerName = this._get(rowData, 'realName', '');
          this.form.repairer = this._get(rowData, 'id', '');
          break;
        default:
          break;
      }
    },
    // 上传前方法
    uploadBefore(file, done, loading, column) {
      if (file.name.split('.')[1] != 'png' && file.name.split('.')[1] != 'jpeg' && file.name.split('.')[1] != 'jpg') {
        this.$message({
          type: 'warning',
          message: '只能上传png/jpeg/jpg文件！'
        });
        loading();
        return;
      } else {
        if (this.form.resultRepairImageList.length >= 3) {
          this.$message({
            type: 'warning',
            message: '最多支持上传3张！'
          });
          loading();
          return;
        } else {
          done();
        }
      }
    },
    // 上传后方法
    uploadAfter(res, done, loading, column) {
      this.form['imageList'].push({
        attachmentId: res.attachId,
        attachmentUrl: res.link,
        attachmentType: 'PICTURE'
      });
      done();
    },
    uploadDelete(file, column) {
      let fileIndex = Number(file.uid);
      return this.$confirm(`是否确定移除${file.name}？`)
        .then((res) => {
          this.form.imageList.splice(fileIndex, 1);
        })
        .catch(() => {});
    },
    // 重新加载公用表格弹窗组件
    newKey() {
      this.timer = new Date().getTime();
    }
  }
};
</script>

<style lang="scss" scope>
.production-page .avue-group__header {
  display: none;
}
</style>
